package com.zbl.zblproject.erp.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alipay.demo.trade.utils.GoodDateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
import com.zbl.zblproject.core.entity.*;
import com.zbl.zblproject.core.mapper.*;
import com.zbl.zblproject.core.utils.StringUtil;
import com.zbl.zblproject.erp.controller.ErpFinanceLogController;
import com.zbl.zblproject.erp.controller.ErpOrderController;
import com.zbl.zblproject.erp.entity.*;
import com.zbl.zblproject.erp.mapper.*;
import com.zbl.zblproject.erp.service.ErpGoodService;
import com.zbl.zblproject.erp.service.ErpOrderService;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author youlanqiang
 * @version 1.0
 * @date 2018/10/10
 * 出入库订单操作类
 */
@Service
public class ErpOrderServiceImpl implements ErpOrderService {

    @Autowired
    private ErpOweGoodsItemMapper erpOweGoodsItemMapper;

    @Autowired
    private ErpOrderMapper erpOrderMapper;

    @Autowired
    private ErpGoodMapper erpGoodMapper;

    @Autowired
    private BalanceMapper balanceMapper;

    @Autowired
    private ErpOrderItemMapper erpOrderItemMapper;

    @Autowired
    private ErpTempOrderItemMapper tempOrderItemMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private ErpCategoryMapper erpCategoryMapper;


    @Autowired
    private ErpWarehouseItemMapper warehouseItemMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private SmallUnitMapper smallUnitMapper;

    @Autowired
    private ErpGoodService erpGoodService;

    @Autowired
    private ErpWarehouseMapper erpWarehouseMapper;

    @Autowired
    private ErpWarehouseItemMapper erpWarehouseItemMapper;

    @Autowired
    private ErpFinanceLogMapper erpFinanceLogMapper;

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private ErpInventoryOrderMapper erpInventoryOrderMapper;

    private static Logger logger = LoggerFactory.getLogger(ErpOrderService.class);


    @Override
    public boolean updateErpOrderByContext(String orderSn, String context) {
        ErpOrder order = getErpOrder(orderSn);
        if (order == null) {
            return false;
        }
        order.setContext(context);
        return erpOrderMapper.updateById(order) == 1;
    }

    @Override
    public ErpOrder getErpOrder(String orderSn) {
        QueryWrapper<ErpOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_info", orderSn);
        logger.info("查询订单号:{}", orderSn);
        ErpOrder order = erpOrderMapper.selectOne(wrapper);
        return order;
    }

    @Override
    @Transactional
    public synchronized ErpOrder createErpOrder(ErpOrder order, List<ErpOrderItem> items) {
        if (items.isEmpty()) {
            throw new RuntimeException("没有商品,创建失败!");
        }

        //获取订单牌子名称
        int goodsId = items.get(0).getGoodsId();
        String brandNames = Joiner.on(",").skipNulls().join(getItemsBrandName(items));

        /**
         * 订单判断,如果存在则删除以前所有的订单货位重新提交
         */
        QueryWrapper<ErpOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_info", order.getOrderInfo());
        ErpOrder orderTemp = erpOrderMapper.selectOne(wrapper);
        logger.info("创建订单编号:{} 订单的状态:{}", order.getOrderInfo(), order.getStatus());
        if (orderTemp != null) {

            if (orderTemp.getStatus() == ErpOrderStatus.pass.getStatus()) {
                throw new RuntimeException("订单状态异常!");
            }
            orderTemp.setContext(order.getContext());
            QueryWrapper<ErpOrderItem> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("order_id", orderTemp.getOrderId());
            erpOrderItemMapper.delete(wrapper2);
            insertOrderItemByOrderId(items, orderTemp.getOrderId(), order);
            orderTemp.setStatus(order.getStatus());

            //更新订单的BrandName
            orderTemp.setBrandName(brandNames);

            orderTemp.setSupplierName(supplierMapper.selectSupplierNameByGoodsId(goodsId));
            erpOrderMapper.updateById(orderTemp);
            return orderTemp;
        } else {
            logger.info("订单mode:{}", order.getMode());

            //brandName设置
            order.setBrandName(brandNames);

            order.setSupplierName(supplierMapper.selectSupplierNameByGoodsId(goodsId));
            if (1 == erpOrderMapper.insert(order)) {
                insertOrderItemByOrderId(items, order.getOrderId(), order);

            } else {
                throw new RuntimeException("保存订单失败!");
            }
            return order;
        }
    }


    private Set<String> getItemsBrandName(List<ErpOrderItem> items) {
        if (items == null) {
            throw new NullPointerException("items is null");
        }
        Set<String> brands = new HashSet<>();
        for (ErpOrderItem item : items) {
            brands.add(brandMapper.selectBrandNameByGoodsId(item.getGoodsId()));
        }
        return brands;
    }

    /**
     * 将ErpOrderItem插入数据库
     *
     * @param items
     * @param orderId
     */
    @Override
    @Transactional
    public void insertOrderItemByOrderId(List<ErpOrderItem> items, int orderId, final ErpOrder order) {
        items.forEach((x) -> {
            x.setGoodsName(erpGoodMapper.getGoodsNameByGoodsId(x.getGoodsId()));
            if (erpGoodMapper.checkGoodsCanUse(x.getGoodsId()) != 0) {
                throw new RuntimeException(x.getGoodsName() + " 商品被禁用!");
            }
            // 判断货位上的商品够不够已经能否入库
            if (order.getMode() == ErpOrderController.MODE_IN) {
                //入库   判断货位上有没有其他商品
                // goodsListId 为4 表示为临时仓位
                if (x.getGoodsList() != 4) {
                    int count = erpWarehouseMapper.foundGoodsCountInWarehouse(x.getGoodsId(), x.getGoodsList());
                    QueryWrapper<ErpWarehouseItem> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("wh_id", x.getGoodsList());
                    List<ErpWarehouseItem> erpWarehouseItems = erpWarehouseItemMapper.selectList(queryWrapper);
                    if (count != 0) {
                        String rs = "";
                        for (ErpWarehouseItem erpWarehouseItem : erpWarehouseItems) {
                            if (erpWarehouseItem.getStock() != 0) {
                                rs += erpGoodMapper.selectById(erpWarehouseItem.getGoodsId()).getGoodsName() + " ";
                            }
                        }
                        throw new RuntimeException(x.getGoodsName() + " 选择的货位上已有其他商品！货位上的商品有:" + rs);
                    }
                }
            } else if (order.getMode() == ErpOrderController.MODE_OUT) {
                //出库   判断有没有库存
                Integer stock = erpWarehouseMapper.foundStockInWarehouse(x.getGoodsId(), x.getGoodsList());
                if (stock == null) {
                    stock = 0;
                }
                if (stock.intValue() < x.getGoodsNum()) {
                    throw new RuntimeException(x.getGoodsName() + " 选择的货位上商品数量不够, 货位只存在:" + stock + "个商品!");
                }
            }

            x.setOrderId(orderId);
            x.setBrandName(erpGoodMapper.getBrandNameByGoodsId(x.getGoodsId()));
            x.setOrderSn(order.getOrderInfo());
            x.setSuppliersId(supplierMapper.selectSupplierIdByGoodsId(x.getGoodsId()));
            erpOrderItemMapper.insert(x);
        });
    }

    @Override
    public List<ErpOrder> selectErpOrderByBrandName(String brandName, int mode, int status) {
        Integer id = brandMapper.selectIdByBrandName(brandName);
        Preconditions.checkNotNull(id, "没有发现对应品牌名的ID.");
        List<ErpOrder> orders = erpOrderMapper.selectErpOrdersByStatusAndModeAndBrandName(id, mode, status);
        return orders;
    }

    @Override
    @Transactional
    public boolean rollbackOrder(String orderInfo) {
        QueryWrapper<ErpOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_info", orderInfo);
        ErpOrder order = erpOrderMapper.selectOne(wrapper);
        if (order == null) {
            throw new RuntimeException("无法查询到对应订单");
        }
        int status = order.getStatus();
        if (status == ErpOrderStatus.pass.getStatus()) {
            throw new RuntimeException("订单已完成无法回滚!");
        }
        if (status == ErpOrderStatus.financeFinish.getStatus()) {
            throw new RuntimeException("财务审核已完成无法回滚!");
        }
        if (status == ErpOrderStatus.finance.getStatus()) {
            if (1 == erpOrderMapper.updateOrderStatus(order.getOrderId(), ErpOrderStatus.submit.getStatus())) {
                //待财务审核回滚到审核中
                erpFinanceLogMapper.updateLogStatusByOrderSn(orderInfo, ErpOrderStatus.returnOrder.getStatus());
                long checkTime = GoodDateUtil.dateToStamp2(erpFinanceLogMapper.selectLogByOrderSn(orderInfo).getChecktime()) / 1000;
                if (checkTime >= ErpFinanceLogController.TIME) {
                    List<ErpOrderItem> orderItems = erpOrderItemMapper.seleteItemsByOrderSns(orderInfo);
                    for (ErpOrderItem orderItem : orderItems) {
                        ErpGoods goods = erpGoodMapper.selectById(orderItem.getGoodsId());
                        goods.setGoodsNumber(goods.getGoodsNumber() + orderItem.getGoodsNum());
                        erpGoodMapper.updateById(goods);
                        erpWarehouseItemMapper.updateStock1(goods.getWhId(), goods.getGoodsId(), orderItem.getGoodsNum());
                        OrderItem orderItem1 = null;
                        if (orderItem.getOrderItemId() != 0) {
                            orderItem1 = orderItemMapper.selectById(orderItem.getOrderItemId());
                            orderItem1.setIsInto(0);
                            orderItem1.setIsOut(0);
                            orderItemMapper.updateById(orderItem1);
                        }
                    }
                    if (!StringUtil.isNullOrEmpty(order.getOriginOrderSn())) {
                        Order order1 = orderMapper.selectByOrderSn(order.getOriginOrderSn());
                        order1.setIsOut(0);
                        order1.setStatus(0);
                        orderMapper.updateById(order1);
                    }
                }
                return true;
            } else {
                throw new RuntimeException("订单更新失败!");
            }
        }
        if (status == ErpOrderStatus.submit.getStatus()) {
            if (1 == erpOrderMapper.updateOrderStatus(order.getOrderId(), ErpOrderStatus.draft.getStatus())) {
                return true;
            } else {
                throw new RuntimeException("订单更新失败!");
            }
        }
        return false;
    }


    @Override
    public List<ErpTempOrderItem> getOrderItemByOrder(String orderInfo) {
        QueryWrapper<ErpOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_info", orderInfo);
        ErpOrder order = erpOrderMapper.selectOne(wrapper);
        if (order == null) {
            throw new RuntimeException("没有发现订单!");
        }
        List<ErpTempOrderItem> items = tempOrderItemMapper.listByOrderItem(order.getOrderId());
        items.forEach(x -> {
            ErpGoods goods = erpGoodMapper.selectById(x.getGoodsId());
            x.setBrandName(brandMapper.selectById(goods.getBrandId()).getBrandName());
            x.setSupplier(supplierMapper.selectById(goods.getSuppliersId()));
            SmallUnit unit = smallUnitMapper.selectById(goods.getSmallunitId());
            if (unit != null) {
                x.setGoodsUnit(unit.getName());
            } else {
                x.setGoodsUnit("件");
            }
            Integer num = Optional.ofNullable(orderItemMapper.selectGoodsNumber(x.getOrderItemId())).orElse(0);
            x.setOriginGoodsNum(num);
            Integer erpOrderItemId = x.getErpOrderItemId();
            Integer goodsNum = erpOrderItemMapper.selectGoodsNumber(erpOrderItemId);
            x.setGoodsNum(goodsNum);
            x.setOriginGoodsNum(num);
            x.setGoodsSn(goods.getGoodsSn());
            x.setStock(goods.getGoodsNumber());
            x.setNumberUnit(String.valueOf(goods.getNumberUnit()));
            x.setLogisticsCostRatio(order.getLogisticsCostRatio());
        });
        return items;
    }

    @Override
    public List<ErpTempOrderItem> getOrderItemByOrders(String orderInfo) {
        QueryWrapper<ErpOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_info", orderInfo);
        ErpOrder order = erpOrderMapper.selectOne(wrapper);
        if (order == null) {
            throw new RuntimeException("没有发现订单!");
        }
        List<ErpTempOrderItem> items = tempOrderItemMapper.listByOrderItems(order.getOrderId());
        items.forEach(x -> {
            ErpGoods goods = erpGoodMapper.selectById(x.getGoodsId());
            x.setBrandName(brandMapper.selectById(goods.getBrandId()).getBrandName());
            x.setSupplier(supplierMapper.selectById(goods.getSuppliersId()));
            SmallUnit unit = smallUnitMapper.selectById(goods.getSmallunitId());
            if (unit != null) {
                x.setGoodsUnit(unit.getName());
            } else {
                x.setGoodsUnit("件");
            }
            Integer num = Optional.ofNullable(orderItemMapper.selectGoodsNumber(x.getOrderItemId())).orElse(0);
            x.setOriginGoodsNum(num);
            Integer erpOrderItemId = x.getErpOrderItemId();
            Integer goodsNum = erpOrderItemMapper.selectGoodsNumber(erpOrderItemId);
            x.setGoodsNum(goodsNum);
            x.setOriginGoodsNum(num);
            x.setGoodsSn(goods.getGoodsSn());
            x.setStock(goods.getGoodsNumber());
            x.setNumberUnit(String.valueOf(goods.getNumberUnit()));
            x.setLogisticsCostRatio(order.getLogisticsCostRatio());

        });
        return items;
    }


    @Override
    public List<ErpTempOrderItem> getOrderItemByOrderNotDesc(String orderInfo) {
        QueryWrapper<ErpOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_info", orderInfo);
        ErpOrder order = erpOrderMapper.selectOne(wrapper);
        if (order == null) {
            ErpInventoryOrder orders = erpInventoryOrderMapper.selectByInSn(orderInfo);
            if (orders == null) {
                throw new RuntimeException("没有发现订单!");
            }
            List<ErpTempOrderItem> items = tempOrderItemMapper.listByOrderItemNotDescs(orders.getId());
            items.forEach(x -> {
                ErpGoods goods = erpGoodMapper.selectById(x.getGoodsId());
                x.setBrandName(brandMapper.selectById(goods.getBrandId()).getBrandName());
                x.setSupplier(supplierMapper.selectById(goods.getSuppliersId()));
                SmallUnit unit = smallUnitMapper.selectById(goods.getSmallunitId());
                if (unit != null) {
                    x.setGoodsUnit(unit.getName());
                } else {
                    x.setGoodsUnit("件");
                }
                x.setGoodsSn(goods.getGoodsSn());
                x.setStock(goods.getGoodsNumber());
                x.setNumberUnit(String.valueOf(goods.getNumberUnit()));
                x.setIsTh(1);
            });
            return items;
        }
        List<ErpTempOrderItem> items = tempOrderItemMapper.listByOrderItemNotDesc(order.getOrderId());
        items.forEach(x -> {
            x.setLogisticsCostRatio(order.getLogisticsCostRatio());
            ErpGoods goods = erpGoodMapper.selectById(x.getGoodsId());
            x.setBrandName(brandMapper.selectById(goods.getBrandId()).getBrandName());
            x.setSupplier(supplierMapper.selectById(goods.getSuppliersId()));
            SmallUnit unit = smallUnitMapper.selectById(goods.getSmallunitId());
            if (unit != null) {
                x.setGoodsUnit(unit.getName());
            } else {
                x.setGoodsUnit("件");
            }
            Integer num = Optional.ofNullable(orderItemMapper.selectGoodsNumber(x.getOrderItemId())).orElse(0);
            x.setOriginGoodsNum(num);
            Integer erpOrderItemId = x.getErpOrderItemId();
            Integer goodsNum = erpOrderItemMapper.selectGoodsNumber(erpOrderItemId);
            x.setGoodsNum(goodsNum);
            x.setGoodsSn(goods.getGoodsSn());
            x.setStock(goods.getGoodsNumber());
            x.setNumberUnit(String.valueOf(goods.getNumberUnit()));
            x.setSupplierName(x.getSupplier().getSuppliersName());
            x.setCatName(erpCategoryMapper.selectById(goods.getCatId()).getCatName());
            x.setShopPrice(goods.getShopPrice());
        });
        return items;
    }


    @Override
    @Transactional
    public boolean deleteOrder(int id) {
        ErpOrder order = erpOrderMapper.selectById(id);
        if (order == null) {
            return false;
        }
        if (order.getStatus() == 3) {
            return false;
        }
        QueryWrapper<ErpOrderItem> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", order.getOrderId());
        erpOrderItemMapper.delete(wrapper);
        erpOrderMapper.deleteById(order.getOrderId());
//        if (order.getOriginOrderSn().contains("CGDD")){
//            orderItemMapper.updateIsInTo(order.getOriginOrderSn(),0);
//        }else if (null!=order.getOriginOrderSn()&&!"".equals(order.getOriginOrderSn())){
//            orderItemMapper.updateIsOut(order.getOriginOrderSn(),0);
//        }
        return true;
    }


    @Override
    public List<Order> getUserOrdersByNotDeliver(int deliver) {
        List<Order> orders = supplierOrdersByCanUses(deliver);
        return orders;
    }

    @Override
    public List<Order> getUserOrdersByIsConfirm(int deliver) {
        Stopwatch watch = Stopwatch.createStarted();
        List<Order> orders = supplierOrdersByCanUseAndISConfirm(deliver);
        watch.stop();
        logger.info("confirm-list 使用时间:{}", watch.toString());
        return orders;
    }

    @Override
    public List<Order> getUserOrdersDesc() {

        List<Order> result = orderMapper.selectStoreConfirmByDeliverZero();
        logger.info("查询出的数据:{}", result.size());
        for (Order x : result) {
            x.setSupplierName(supplierMapper.selectSupplierNameByOrderSn(x.getOrderSn()));
            x.setUser(adminUserMapper.selectUserById(x.getUserId()));
        }
        return result;
    }

    @Override
    public PageInfo getOrdersByNotDeliver(int pageCur, int pageSize, int deliver, int mode) {
        Stopwatch watch = Stopwatch.createStarted();
        PageInfo pageInfo = null;
        if (mode == 0) {
            pageInfo = orderListPage(pageCur, pageSize, deliver);
        } else {
            pageInfo = supplierOrdersByCanUse(pageCur, pageSize, deliver);
        }
        watch.stop();
        logger.info("getOrdersByNotDeliver 耗时:{}", watch.toString());
        return pageInfo;
    }

    @Override
    public List<Supplier> getSupplierByNotDeliver(int pageCur, int pageSize, int deliver, int mode) {

        List<Order> orders;
        if (mode == 0) {
            orders = ordersByCanUse(pageCur, pageSize, deliver);
        } else {
            orders = supplierOrdersByCanUses(deliver);
        }
        Map<String, Supplier> map = new HashMap<>();
        ErpTempOrderItem tempItem;
        for (Order order : orders) {
            for (ErpTempOrderItem item : order.getItems()) {
                Supplier supplier = item.getSupplier();
                if (map.containsKey(supplier.getSuppliersName())) {
                    supplier = map.get(supplier.getSuppliersName());
                    tempItem = item.cloneNew();
                    tempItem.setSupplier(null);
                    supplier.getItems().add(tempItem);
                } else {
                    Supplier newSupplier = supplier.cloneNew();
                    tempItem = item.cloneNew();
                    tempItem.setSupplier(null);
                    newSupplier.getItems().add(tempItem);
                    map.put(supplier.getSuppliersName(), newSupplier);
                }
            }
        }

        return Lists.newArrayList(map.values());
    }


    /**
     * 查询出所有的没有入库的订单
     *
     * @return
     */
    @Override
    public List<Order> ordersByCanUse(int pageCur, int pageSize, int deliver) {
        List<Order> orders = orderMapper.selectOrdersByCanUse(deliver);
        orders.forEach(x -> {
            x.setUser(adminUserMapper.selectById(x.getUserId()));
            x.setItems(getTempOrderByOrderSnAndNotInto(x.getOrderSn()));
            Supplier supplier = x.getItems().get(0).getSupplier();
            if (supplier != null) {
                x.setSupplierName(supplier.getSuppliersName());
            } else {
                x.setSupplierName("");
            }
        });
        //1.939 s -- 357.1 ms
        return orders;
    }

    @Override
    public PageInfo orderListPage(int pageCur, int pageSize, int deliver) {
        PageHelper.startPage(pageCur, pageSize);
        List<Order> orders = orderMapper.selectOrdersByCanUse(deliver);
        orders.forEach(x -> {
            x.setUser(adminUserMapper.selectById(x.getUserId()));
            x.setItems(getTempOrderByOrderSnAndNotInto(x.getOrderSn()));
            Supplier supplier = x.getItems().get(0).getSupplier();
            if (supplier != null) {
                x.setSupplierName(supplier.getSuppliersName());
            } else {
                x.setSupplierName("");
            }
        });
        //1.939 s -- 357.1 ms
        PageInfo pageInfo = new PageInfo(orders);
        return pageInfo;
    }


    @Override
    public List<Order> supplierOrdersByCanUseAndISConfirm(int deliver) {

        List<Order> result = orderMapper.selectStoreConfirmByDeliver(deliver);
        for (Order x : result) {
            x.setItems(getTempOrderByOrderSnAndNotOut(x.getOrderSn()));
            x.setSupplierName(x.getItems().get(0).getSupplier().getSuppliersName());
            x.setUser(adminUserMapper.selectUserById(x.getUserId()));
        }
        return result;
    }

    @Override
    public PageInfo supplierOrdersByCanUse(int pageCur, int pageSize, int deliver) {
//        QueryWrapper<Order> orderWrapper = new QueryWrapper<>();
//        orderWrapper.eq("is_pay", 1).eq("is_cancel", 0).eq("is_deliver", deliver).notLike("order_sn", "CGDD");
//        List<Order> orders = orderMapper.selectList(orderWrapper);
//        orders.forEach(x -> {
//            x.setUser(adminUserMapper.selectById(x.getUserId()));
//            x.setItems(getTempOrderByOrderSnAndNotOut(x.getOrderSn()));
//        });
//
//        return orders.stream().filter(x -> {
//            return !x.getItems().isEmpty();
//        }).collect(Collectors.toList());
        PageHelper.startPage(pageCur, pageSize);
        List<Order> orders = orderMapper.selectSupplierOrdersByCanUse(deliver);
        orders.forEach(x -> {
            x.setUser(adminUserMapper.selectById(x.getUserId()));
            x.setItems(getTempOrderByOrderSnAndNotOut(x.getOrderSn()));
        });
        PageInfo pageInfo = new PageInfo(orders);
        return pageInfo;
    }

    @Override
    public List<Order> supplierOrdersByCanUses(int deliver) {
//        QueryWrapper<Order> orderWrapper = new QueryWrapper<>();
//        orderWrapper.eq("is_pay", 1).eq("is_cancel", 0).eq("is_deliver", deliver).notLike("order_sn", "CGDD");
//        List<Order> orders = orderMapper.selectList(orderWrapper);
//        orders.forEach(x -> {
//            x.setUser(adminUserMapper.selectById(x.getUserId()));
//            x.setItems(getTempOrderByOrderSnAndNotOut(x.getOrderSn()));
//        });
//
//        return orders.stream().filter(x -> {
//            return !x.getItems().isEmpty();
//        }).collect(Collectors.toList());
        List<Order> orders = orderMapper.selectSupplierOrdersByCanUse(deliver);
        orders.forEach(x -> {
            x.setUser(adminUserMapper.selectById(x.getUserId()));
            x.setItems(getTempOrderByOrderSnAndNotOut(x.getOrderSn()));
        });
        return orders;
    }

    /**
     * 根据OrderSn来查询ErpTempOrderItem
     *
     * @param orderSn 订单的SN
     * @return
     */
    @Override
    public List<ErpTempOrderItem> getTempOrderByOrderSn(String orderSn) {
        QueryWrapper<OrderItem> itemWrapper = new QueryWrapper<>();
        itemWrapper.eq("order_sn", orderSn);
        List<OrderItem> list = orderItemMapper.selectList(itemWrapper);
        final List<ErpTempOrderItem> items = new ArrayList<>(list.size());
        list.forEach(x -> {
            items.add(orderItem2TempItem(x));
        });
        return items;
    }

    /**
     * 根据OrderSn来查询没有入库的ErpTempOrderItem
     *
     * @param orderSn
     * @return
     */
    @Override
    public List<ErpTempOrderItem> getTempOrderByOrderSnAndNotInto(String orderSn) {
//        QueryWrapper<OrderItem> itemWrapper = new QueryWrapper<>();
//        itemWrapper.eq("order_sn", orderSn).eq("is_into", 0);
//        List<OrderItem> list = orderItemMapper.selectList(itemWrapper);
//        final List<ErpTempOrderItem> items = new ArrayList<>(list.size());
//        list.forEach(x -> {
//            items.add(orderItem2TempItem(x));
//        });
//        return items;
        List<ErpTempOrderItem> list = orderItemMapper.selectErpTempOrderItemByOrderSnAndIsInto(orderSn, 0);
        for (ErpTempOrderItem erpTempOrderItem : list) {
            ErpGoods erpGoods = erpGoodMapper.selectById(erpTempOrderItem.getGoodsId());
            erpTempOrderItem.setDefaultWarehouse(erpWarehouseMapper.selectListOfSearchs(erpGoods.getWhId()));
        }
        return list;
    }


    /**
     * 根据OrderSn来查询没有出库的ErpTempOrderItem
     *
     * @param orderSn
     * @return
     */
    @Override
    public List<ErpTempOrderItem> getTempOrderByOrderSnAndNotOut(String orderSn) {
//        QueryWrapper<OrderItem> itemWrapper = new QueryWrapper<>();
//        itemWrapper.eq("order_sn", orderSn).eq("is_out", 0);
//        List<OrderItem> list = orderItemMapper.selectList(itemWrapper);
//        final List<ErpTempOrderItem> items = new ArrayList<>(list.size());
//        list.forEach(x -> {
//           items.add(orderItem2TempItem(x));
//        });
//        return items;
        //if(orderItemMapper.selectOrderSnAndIsOutSum(orderSn,0 ) != 0) {
        List<ErpTempOrderItem> list = orderItemMapper.selectErpTempOrderItemByOrderSn(orderSn, 0);
        for (ErpTempOrderItem erpTempOrderItem : list) {
            ErpGoods erpGoods = erpGoodMapper.selectById(erpTempOrderItem.getGoodsId());
            ErpWarehouse erpWarehouse = erpWarehouseMapper.selectListOfSearchs(erpGoods.getWhId());
            erpTempOrderItem.setDefaultWarehouse(erpWarehouse);
        }
        return list;
//        }
//        return null;
    }


    /**
     * 根据OrderSn来查询ErpTempOrderItem
     *
     * @param orderSn 订单的SN
     * @return
     */
    @Override
    public List<ErpTempOrderItem> getTempOrderByOrderSnAndNotPurchasing(String orderSn) {
//        QueryWrapper<OrderItem> itemWrapper = new QueryWrapper<>();
//        itemWrapper.eq("order_sn", orderSn).eq("is_purchasing", "0");
//        List<OrderItem> list = orderItemMapper.selectList(itemWrapper);
//        final List<ErpTempOrderItem> items = new ArrayList<>(list.size());
//
//        list.forEach(x -> {
//            items.add(orderItem2TempItem(x));
//        });
//        return items;
        return orderItemMapper.selectErpTempOrderItemByOrderSnAndPurch(orderSn, 0);
    }

    @Override
    public ErpTempOrderItem orderItem2TempItem(OrderItem x) {
        ErpTempOrderItem orderItem = new ErpTempOrderItem();
        orderItem.setGoodsId(x.getGoodsId());
        orderItem.setGoodsList(0);
        orderItem.setGoodsListName("");
        orderItem.setGoodsName(x.getGoodsName());
        orderItem.setGoodsNum(x.getGoodsNum());
        orderItem.setGoodsPrice(x.getShopPrice());
        orderItem.setBrandName(x.getBrandName());
        orderItem.setOrderItemId(x.getId());
        orderItem.setGoodsDesc(x.getGoodsDesc());
        orderItem.setIsInto(x.getIsInto());

        ErpGoods goods = erpGoodMapper.selectById(x.getGoodsId());
        String spe = "";
        if (goods != null) {
            spe = goods.getSpecifications();
            orderItem.setStock(goods.getGoodsNumber());
            orderItem.setPAddress(goods.getPAddress());
            orderItem.setSupplier(supplierMapper.selectById(goods.getSuppliersId()));
        } else {
            orderItem.setStock(0);
            orderItem.setPAddress("");
            orderItem.setSupplier(new Supplier());
        }
        orderItem.setNumberUnit(String.valueOf(goods.getNumberUnit()));
        orderItem.setSpecifications(spe);

        //brandMapper.selectCentralizedPurchasing(x.getBrandName())
        Integer centralized = Optional.ofNullable(brandMapper.selectCentralizedPurchasing(x.getBrandName())).orElse(0);
        orderItem.setCentralizedPurchasing(centralized);
        orderItem.setDefaultWarehouse(erpWarehouseMapper.selectDefaultWarehouseByGoodsId(x.getGoodsId()));
        //小单位
        SmallUnit smallUnit = smallUnitMapper.selectById(goods.getSmallunitId());
        if (smallUnit == null) {
            orderItem.setGoodsUnit("件");
        } else {
            orderItem.setGoodsUnit(smallUnit.getName());
        }
        return orderItem;
    }

    @Override
    public IPage<ErpOrder> erpOrderList(String search, int current, int size) {

        Page page = new Page(current, size);
        IPage<ErpOrder> orders = erpOrderMapper.selectPageBySearch(page, search);
        orders.getRecords().forEach((x) -> {
            DecimalFormat df = new DecimalFormat("#0.00");
            if (erpOrderMapper.selectOrderTotal(x.getOrderId()) != null) {
                x.setTotal(df.format(erpOrderMapper.selectOrderTotal(x.getOrderId())));
                QueryWrapper<ErpOrderItem> wrapper = new QueryWrapper<>();
                wrapper.eq("order_sn", x.getOrderInfo());
                List<ErpOrderItem> erpOrderItem = erpOrderItemMapper.selectList(wrapper);
                long time = java.sql.Timestamp.valueOf(x.getCreateTime()).getTime() / 1000;
                if (erpOrderItem.size() > 0 && time >= 1562025600) {
                    double total = 0;
                    if (x.getMode() == 1) {
                        total = x.getLogisticsCostRatio().doubleValue() * Double.valueOf(x.getTotal()) + Double.valueOf(x.getTotal());
                    } else {
                        total = Double.valueOf(x.getTotal());
                    }

                    x.setTotal(String.valueOf(total));
                }

            } else {
                x.setTotal("0");
            }
            x.setStoreName(adminUserMapper.selectNameById(x.getStoreId()));
        });
        return orders;
    }


    @Override
    @Transactional
    public ErpOrder passOrder(String orderInfo, int userId) {
        QueryWrapper<ErpOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_info", orderInfo);
        final ErpOrder order = erpOrderMapper.selectOne(wrapper);
        if (order == null) {
            throw new RuntimeException("无法查询到对应订单");
        }
        int status = order.getStatus();

        if (order.getMode() == ErpOrderController.MODE_IN) {
            //调用入库步骤
            modeIn(order, status, userId);
        } else if (order.getMode() == ErpOrderController.MODE_OUT) {
            //调用出库步骤
            modeOut(order, status, userId);
            // modeOutOld(order, status, userId);
        } else if (order.getMode() == ErpOrderController.MODE_RETURN) {
            //退货单操作

        }
        if (erpOrderMapper.updateById(order) == 1) {
            return order;
        }
        throw new RuntimeException("订单更新失败!");
    }

    private void modeIn(final ErpOrder order, int status, int userId) {

        //入库单操作
        if (status == ErpOrderStatus.draft.getStatus()) {
            //草稿状态 -- 提交申请
            order.setStatus(ErpOrderStatus.submit.getStatus());

        } else if (status == ErpOrderStatus.finance.getStatus()) {
            //财务审核到 -- 订单审核
            throw new RuntimeException("入库单没有财务审核!");

        } else if (status == ErpOrderStatus.submit.getStatus()) {

            //状态由带审核变成审核成功
            AdminUser user = adminUserMapper.selectById(userId);
            Preconditions.checkNotNull(user, "用户不存在。");

            //提交申请 -- 通过
            //更新订单所有的数值
            QueryWrapper<ErpOrderItem> itemWrapper = new QueryWrapper<>();
            itemWrapper.eq("order_id", order.getOrderId());
            List<ErpOrderItem> items = erpOrderItemMapper.selectList(itemWrapper);

            int allGoodsNum = 0;
            String orderSn = null;
            for (ErpOrderItem x : items) {
                ErpGoods goods = erpGoodMapper.selectById(x.getGoodsId());
                logger.info("商品的GoodsNum : {}", x.getGoodsNum());
                allGoodsNum = allGoodsNum + x.getGoodsNum();
                if (goods != null) {
                    ErpWarehouseItem item = warehouseItemMapper.selectItemByGoodsIdAndWhId(x.getGoodsId(), x.getGoodsList());
                    logger.info("goods的ID:{} 名称:{} 数量:{} 待减数量:{} 缺货数量:{}",
                            goods.getGoodsId(), goods.getGoodsName(), goods.getGoodsNumber(), x.getGoodsNum(), x.getOweNum());
                    //根据订单的类型判断是添加还是删除
                    OrderItem orderItem = null;
                    if (x.getOrderItemId() != 0) {
                        orderItem = orderItemMapper.selectById(x.getOrderItemId());
                    }

                    //入库
                    goods.setGoodsNumber(goods.getGoodsNumber() + x.getGoodsNum());
                    if (orderItem != null) {
                        // logger.info("orderItem:{}", orderItem);
                        orderItem.setIsInto(1);
                        orderItem.setIsOut(1);
                        orderSn = orderItem.getOrderSn();

                        orderItemMapper.updateById(orderItem);

                        if (orderItem.getGoodsNum() < x.getGoodsNum()) {
                            int excess = x.getGoodsNum() - orderItem.getGoodsNum();
                            //超额金额
                            BigDecimal price = orderItem.getShopPrice().multiply(BigDecimal.valueOf(excess));
                            //添加供应商金额
                            logger.info("supplierID:{} 添加金额:{}",
                                    x.getSuppliersId(), price);
                            supplierMapper.addSuplierBalance(x.getSuppliersId(), price);
                        }
                    }

                    //对仓库商品进行修改 如果存在便添加商品,如果不存在就创建商品

                    if (x.getOweItem() == 0) {
                        intserOrUpdateWarehouseItem(item, x);
                        //欠货
                        oweGoodsByIn(orderItem, x, order, userId, goods.getSuppliersId());
                    } else {
                        ErpOweGoodsItem oweGoodsItem = erpOweGoodsItemMapper.selectById(x.getOweItem());
                        if (oweGoodsItem == null) {
                            throw new RuntimeException("没有发现这个欠货列");
                        }
                        if (oweGoodsItem.getNumber() >= x.getGoodsNum()) {
                            Preconditions.checkArgument(erpGoodService.replenishGoods(oweGoodsItem.getId(), x.getGoodsNum()), "还货失败!");
                            x.setDefaultMsg("还货-- 商品ID:" + x.getGoodsId()
                                    + " 还货数量:" + x.getGoodsNum() + " 欠货单号:" + oweGoodsItem.getOrderSn() + " 欠货ID:" + oweGoodsItem.getId());
                        } else {
                            Preconditions.checkArgument(erpGoodService.replenishGoods(oweGoodsItem.getId(), oweGoodsItem.getNumber()), "还货失败!");
                            x.setDefaultMsg("还货-- 商品ID:" + x.getGoodsId()
                                    + " 还货数量:" + x.getGoodsNum() + " 欠货单号:" + oweGoodsItem.getOrderSn() + " 欠货ID:" + oweGoodsItem.getId());
                        }
                        erpOrderItemMapper.updateById(x);
                        intserOrUpdateWarehouseItem(item, x);
                    }
                    Balance balance = new Balance();
                    long createTiem = System.currentTimeMillis() / 1000;
                    balance.setCreateTime(createTiem);
                    balance.setGoodsId(goods.getGoodsId());
                    balance.setGoodsName(goods.getGoodsName());
                    balance.setGoodsNum(x.getGoodsNum());
                    if (x.getIsGive() == 1) {
                        balance.setShopPrice(BigDecimal.ZERO);
                    } else {
                        balance.setShopPrice(x.getGoodsPrice());
                    }
                    if (goods.getWhId() == 0) {
                        goods.setWhId(x.getGoodsList());
                    }
                    balanceMapper.insert(balance);
                    erpGoodMapper.updateById(goods);
                }
            }
            if (!"".equals(order.getOriginOrderSn()) && order.getOriginOrderSn() != null) {
                //OrderSn订单状态更新
                allGoodsNum = allGoodsNum + erpOrderItemMapper.selectGoodsNumForOriginOrderSnAndStatus(order.getOriginOrderSn(), 2);

                int originOrderNumber = orderItemMapper.selectOriginOrderNumber(order.getOriginOrderSn());
                logger.info("Origin Order Number: {}  All Goods Num: {}", originOrderNumber, allGoodsNum);
                if (allGoodsNum >= originOrderNumber) {
                    // status = 2; 已完成
                    orderMapper.updateOrderStatus(order.getOriginOrderSn(), OrderStatus.completed.getStatus());
                } else if (allGoodsNum >= 0) {
                    // status = 1; 部分销售
                    orderMapper.updateOrderStatus(order.getOriginOrderSn(), OrderStatus.partialSales.getStatus());
                }
            }
//            if (!items.isEmpty()) {
//                for (ErpOrderItem item : items) {
//                    insertOutOrInOweGoods(item, userId, order.getMode());
//                }
//            }


            order.setStatus(ErpOrderStatus.pass.getStatus());
            //设置执行者姓名和执行时间.
            order.setExecuteTime(LocalDateTime.now());
            order.setExecutor(user.getUserName());
        } else {
            throw new RuntimeException("订单状态异常!");
        }
    }

    /**
     * 处理出库订单类型
     *
     * @param order
     * @param status
     * @param userId
     * @return
     */
    private void modeOut(final ErpOrder order, int status, int userId) {
        AdminUser user = adminUserMapper.selectById(userId);
        Preconditions.checkNotNull(user, "用户不存在。");
        //出库单操作
        if (status == ErpOrderStatus.draft.getStatus()) {
            //草稿状态 -- 提交申请
            order.setStatus(ErpOrderStatus.submit.getStatus());
        } else if (status == ErpOrderStatus.submit.getStatus()) {
            //财务审核到 -- 订单审核
            AdminUser store = adminUserMapper.selectById(order.getStoreId());
            QueryWrapper<ErpOrderItem> wrapper = new QueryWrapper<>();
            wrapper.eq("order_sn", order.getOrderInfo());
            List<ErpOrderItem> erpOrderItems = erpOrderItemMapper.selectList(wrapper);
            ErpOrderItem erpOrderItem = erpOrderItems.get(0);
            ErpFinanceLog log = new ErpFinanceLog();
            log.setOrderNumber("SK" + Instant.now().toEpochMilli());
            log.setOrderSn(order.getOrderInfo());
            log.setSupplierName(String.valueOf(erpOrderItem.getSuppliersId()));
            log.setChecktime(LocalDateTime.now());
            Supplier supplier = supplierMapper.selectById(erpOrderItem.getSuppliersId());
            double total = erpOrderMapper.selectOrderTotal(order.getOrderId()).doubleValue()
                    + erpOrderMapper.selectOrderTotal(order.getOrderId()).doubleValue() * order.getLogisticsCostRatio().doubleValue();
            log.setTotal(BigDecimal.valueOf(total));
            log.setStatus(ErpOrderStatus.submit.getStatus());
            log.setStoreName(String.valueOf(store.getUserId()));
            log.setMode(ErpFinanceLog.MODE_RECEIPT);
            log.setRemark(order.getContext());
            //初始化反点金额
            BigDecimal rebateRate = store.getRebateRate();
            if (rebateRate == null || rebateRate.doubleValue() == 0.0) {
                rebateRate = BigDecimal.ZERO;
            }

            BigDecimal rebate = log.getSubTotal().multiply(rebateRate);
            log.setRebate(rebate);
            log.setUserBalance(store.getBalance());
            log.setCreater(user.getUserName());
            erpFinanceLogMapper.insert(log);


            //更新订单所有的数值
            QueryWrapper<ErpOrderItem> itemWrapper = new QueryWrapper<>();
            itemWrapper.eq("order_id", order.getOrderId());
            List<ErpOrderItem> items = erpOrderItemMapper.selectList(itemWrapper);
            items.forEach((x) -> {
                OrderItem orderItem = null;
                if (x.getOrderItemId() != 0) {
                    orderItem = orderItemMapper.selectById(x.getOrderItemId());
                }
                ErpGoods goods = erpGoodMapper.selectById(x.getGoodsId());
                if (goods != null) {
                    ErpWarehouseItem item = warehouseItemMapper.selectItemByGoodsIdAndWhId(x.getGoodsId(), x.getGoodsList());
//                    logger.info("goods的ID:{} 名称:{} 数量:{} 待减数量:{} 缺货数量:{}",
//                            goods.getGoodsId(), goods.getGoodsName(), goods.getGoodsNumber(), x.getGoodsNum(), x.getOweNum());
                    //根据订单的类型判断是添加还是删除
//                    OrderItem orderItem = null;
//                    if (x.getOrderItemId() != 0) {
//                        orderItem = orderItemMapper.selectById(x.getOrderItemId());
//                    }

                    //出库
//                    if (x.getOweItem() != 0) {
//                        //还货 要减库存
//                        ErpOweGoodsItem oweGoodsItem = erpOweGoodsItemMapper.selectById(x.getOweItem());
//
//                        if (oweGoodsItem == null) {
//                            throw new RuntimeException("该商品{" + goods.getGoodsName() + "}没有缺货");
//                        }
//
//                        if (oweGoodsItem.getNumber() >= x.getGoodsNum()) {
//                            x.setDefaultMsg("补货-- 商品ID:" + x.getGoodsId()
//                                    + " 补货数量:" + x.getGoodsNum() + " 补货单号:" + oweGoodsItem.getOrderSn() + " 补货ID:" + oweGoodsItem.getId());
//                            erpGoodService.replenishGoods(oweGoodsItem.getId(), x.getGoodsNum());
//                        } else {
//                            x.setDefaultMsg("补货-- 商品ID:" + x.getGoodsId()
//                                    + " 补货数量:" + x.getGoodsNum() + " 补货单号:" + oweGoodsItem.getOrderSn() + " 补货ID:" + oweGoodsItem.getId());
//                            erpGoodService.replenishGoods(oweGoodsItem.getId(), oweGoodsItem.getNumber());
//                        }
//                    }

                    if (x.getGoodsNum() != 0) {

                        if (item == null) {
                            throw new RuntimeException("货架ID:" + x.getGoodsList() + "上没有这个商品{" + goods.getGoodsName() + "}!");
                        } else {

                            if (x.getGoodsNum() > item.getStock()) {
                                throw new RuntimeException("货架ID:" + item.getWhId() + " 上的商品{" + goods.getGoodsName() + "}不够!");
                            }
                            item.setStock(item.getStock() - x.getGoodsNum());
                            warehouseItemMapper.updateById(item);

                        }
                        goods.setGoodsNumber(goods.getGoodsNumber() - x.getGoodsNum());

                        //记录在本月的销售额度中
                        //Integer value = Optional.ofNullable(erpTempOrderItemMapper.countGoodsAmountOfTheBeforeMonth(x.getGoodsId())).orElse(0);
//                        goods.setSoldNumberOfBeforeMonth(value + x.getGoodsNum());
//                        int unixTime = Integer.valueOf("" + System.currentTimeMillis() / 1000);
//                        goods.setLastUpdate(unixTime);
                    }
                    System.out.println(x.getOweItem());


                    //设置为以出库
//                    outStatusChange(orderItem, order);
//                    QueryWrapper<Balance> wrappers = new QueryWrapper<>();
//                    wrapper.eq("goods_id", x.getGoodsId());
//                    wrapper.orderByAsc("create_time");
//                    List<Balance> balances = balanceMapper.selectList(wrappers);
//                    if (balances != null && balances.size() > 0) {
//                        if (balances.size() == 1) {
//                            Balance balance = balances.get(0);
//                            balance.setGoodsNum(balance.getGoodsNum() - x.getGoodsNum());
//                            balanceMapper.updateById(balance);
//                        } else {
//                            int num = x.getGoodsNum();
//                            int tem = 0;
//                            for (Balance balance : balances) {
//                                if (balance.getGoodsNum() < 0) {
//                                    continue;
//                                }
//                                num = num - balance.getGoodsNum();
//                                if (num > 0) {
//                                    balance.setGoodsNum(0);
//                                    balanceMapper.updateById(balance);
//                                } else {
//                                    balance.setGoodsNum((-1) * num);
//                                    balanceMapper.updateById(balance);
//                                    break;
//                                }
//                            }
//                        }
//                    }
                    erpGoodMapper.updateById(goods);
                    erpOrderItemMapper.updateById(x);
                }
            });

            //更新 order1 的 isout
            String orderSn = order.getOriginOrderSn();
            if (orderSn != null && !"".equals(orderSn)) {
                List<OrderItem> orderItems = orderItemMapper.selectListByIsOut(orderSn);
                Order order1 = orderMapper.selectByOrderSn(orderSn);
                if (order1.getIsOut() != 1) {
                    for (OrderItem orderItem : orderItems) {
                        orderItem.setIsOut(1);
                        orderItem.setIsInto(1);
                        orderItemMapper.updateById(orderItem);
                    }
                }
            }
//                Integer count = orderItemMapper.selectCountByIsOut(orderSn);
//                if (count != 0) {
//                    List<OrderItem> orderItems = orderItemMapper.selectListByIsOut(orderSn);
//                    for(OrderItem orderItem : orderItems){
//                        oweGoodsByOut(orderItem, userId);
//                    }
//                }
//                if (order1 != null && order1.getIsOut() != 1) {
//                    order1.setIsOut(1);
//                    orderMapper.updateById(order1);
//                }

//            }

//            if (!items.isEmpty()) {
//                for (ErpOrderItem item : items) {
//                    insertOutOrInOweGoods(item, userId, order.getMode());
//                }
//            }


            //设置origin_order的订单状态
//            if (!StringUtil.isNullOrEmpty(order.getOriginOrderSn())) {
//                updateOrderStatus(order.getOriginOrderSn(), order.getOrderId());
//            }
            order.setCreateTime(LocalDateTime.now());
            order.setStatus(ErpOrderStatus.finance.getStatus());
        } else if (status == ErpOrderStatus.finance.getStatus()) {
            throw new RuntimeException("请在财务页面通过!");
        } else if (status == ErpOrderStatus.financeFinish.getStatus()) {
            //状态由带审核变成审核成功
            //提交申请 -- 通过
            long checkTime = GoodDateUtil.dateToStamp2(order.getCreateTime()) / 1000;
            QueryWrapper<ErpOrderItem> itemWrapper = new QueryWrapper<>();
            itemWrapper.eq("order_id", order.getOrderId());
            List<ErpOrderItem> items = erpOrderItemMapper.selectList(itemWrapper);
            if (checkTime <= ErpFinanceLogController.TIME) {//出库单创建时间小于设置的时间则在最后一步减库存
                //更新订单所有的数值
                items.forEach((x) -> {
                    ErpGoods goods = erpGoodMapper.selectById(x.getGoodsId());
                    if (goods != null) {
                        ErpWarehouseItem item = warehouseItemMapper.selectItemByGoodsIdAndWhId(x.getGoodsId(), x.getGoodsList());
                        if (x.getGoodsNum() != 0) {

                            if (item == null) {
                                throw new RuntimeException("货架ID:" + x.getGoodsList() + "上没有这个商品{" + goods.getGoodsName() + "}!");
                            } else {

                                if (x.getGoodsNum() > item.getStock()) {
                                    throw new RuntimeException("货架ID:" + item.getWhId() + " 上的商品{" + goods.getGoodsName() + "}不够!");
                                }
                                item.setStock(item.getStock() - x.getGoodsNum());
                                warehouseItemMapper.updateById(item);

                            }
                            goods.setGoodsNumber(goods.getGoodsNumber() - x.getGoodsNum());

                            //记录在本月的销售额度中
                            //Integer value = Optional.ofNullable(erpTempOrderItemMapper.countGoodsAmountOfTheBeforeMonth(x.getGoodsId())).orElse(0);
//                        goods.setSoldNumberOfBeforeMonth(value + x.getGoodsNum());
//                        int unixTime = Integer.valueOf("" + System.currentTimeMillis() / 1000);
//                        goods.setLastUpdate(unixTime);
                        }

                        erpGoodMapper.updateById(goods);
                        erpOrderItemMapper.updateById(x);
                    }
                });


            }
            items.forEach((x -> {
                OrderItem orderItem = null;
                if (x.getOrderItemId() != 0) {
                    orderItem = orderItemMapper.selectById(x.getOrderItemId());
                }

                ErpGoods goods = erpGoodMapper.selectById(x.getGoodsId());
                ErpWarehouseItem item = warehouseItemMapper.selectItemByGoodsIdAndWhId(x.getGoodsId(), x.getGoodsList());
//                    logger.info("goods的ID:{} 名称:{} 数量:{} 待减数量:{} 缺货数量:{}",
//                            goods.getGoodsId(), goods.getGoodsName(), goods.getGoodsNumber(), x.getGoodsNum(), x.getOweNum());
                //根据订单的类型判断是添加还是删除
                //出库
                if (x.getOweItem() != 0) {
                    //还货 要减库存
                    ErpOweGoodsItem oweGoodsItem = erpOweGoodsItemMapper.selectById(x.getOweItem());

                    if (oweGoodsItem == null) {
                        throw new RuntimeException("该商品{" + goods.getGoodsName() + "}没有缺货");
                    }

                    if (oweGoodsItem.getNumber() >= x.getGoodsNum()) {
                        x.setDefaultMsg("补货-- 商品ID:" + x.getGoodsId()
                                + " 补货数量:" + x.getGoodsNum() + " 补货单号:" + oweGoodsItem.getOrderSn() + " 补货ID:" + oweGoodsItem.getId());
                        erpGoodService.replenishGoods(oweGoodsItem.getId(), x.getGoodsNum());
                    } else {
                        x.setDefaultMsg("补货-- 商品ID:" + x.getGoodsId()
                                + " 补货数量:" + x.getGoodsNum() + " 补货单号:" + oweGoodsItem.getOrderSn() + " 补货ID:" + oweGoodsItem.getId());
                        erpGoodService.replenishGoods(oweGoodsItem.getId(), oweGoodsItem.getNumber());
                    }
                }


                QueryWrapper<Balance> wrapper = new QueryWrapper<>();
                wrapper.eq("goods_id", x.getGoodsId());
                wrapper.orderByAsc("create_time");
                List<Balance> balances = balanceMapper.selectList(wrapper);
                if (balances != null && balances.size() > 0) {
                    if (balances.size() == 1) {
                        Balance balance = balances.get(0);
                        balance.setGoodsNum(balance.getGoodsNum() - x.getGoodsNum());
                        balanceMapper.updateById(balance);
                    } else {
                        int num = x.getGoodsNum();
                        int tem = 0;
                        for (Balance balance : balances) {
                            if (balance.getGoodsNum() < 0) {
                                continue;
                            }
                            num = num - balance.getGoodsNum();
                            if (num > 0) {
                                balance.setGoodsNum(0);
                                balanceMapper.updateById(balance);
                            } else {
                                balance.setGoodsNum((-1) * num);
                                balanceMapper.updateById(balance);
                                break;
                            }
                        }
                    }
                }
                //设置为以出库
                outStatusChange(orderItem, order);
            }));
            //更新 order1 的 isout
            String orderSn = order.getOriginOrderSn();
            if (orderSn != null && !"".equals(orderSn)) {
                List<OrderItem> orderItems = orderItemMapper.selectListByIsOut(orderSn);
                Order order1 = orderMapper.selectByOrderSn(orderSn);
                if (order1.getIsOut() != 1) {
                    for (OrderItem orderItem : orderItems) {
                        orderItem.setIsOut(1);
                        orderItem.setIsInto(1);
                        orderItemMapper.updateById(orderItem);
//                        int i = 0;
//                        for (ErpOrderItem erpOrderItem : items) {
//                            if (orderItem.getGoodsId() == erpOrderItem.getGoodsId()) {
//                                i++;
//                            }
//                        }
//                        if (i == 0) {
//                            oweGoodsByOut(orderItem, userId);
//                        }
                    }
                }
                Integer count = orderItemMapper.selectCountByIsOut(orderSn);
                if (count != 0) {
//                    List<OrderItem> orderItems = orderItemMapper.selectListByIsOut(orderSn);
//                    for(OrderItem orderItem : orderItems){
//                        oweGoodsByOut(orderItem, userId);
//                    }
                }
                if (order1 != null && order1.getIsOut() != 1) {
                    order1.setIsOut(1);
                    orderMapper.updateById(order1);
                }

            }

//            if (!items.isEmpty()) {
//                for (ErpOrderItem item : items) {
//                    insertOutOrInOweGoods(item, userId, order.getMode());
//                }
//            }


            //设置origin_order的订单状态
            if (!StringUtil.isNullOrEmpty(order.getOriginOrderSn())) {
                updateOrderStatus(order.getOriginOrderSn(), order.getOrderId());
            }
            order.setStatus(ErpOrderStatus.pass.getStatus());
            //设置执行者姓名和执行时间.
            order.setExecuteTime(LocalDateTime.now());
            order.setExecutor(user.getUserName());
        } else {
            throw new RuntimeException("订单状态异常!");
        }
    }


    private void updateOrderStatus(String originOrderSn, int orderId) {
        int orderNum = Optional.ofNullable(orderItemMapper.selectOriginOrderNumber(originOrderSn)).orElse(0);
        int outOrderNum = Optional.ofNullable(
                orderItemMapper.selectOutOrderNumberByOrigin(originOrderSn,
                        orderId,
                        ErpOrderController.MODE_OUT,
                        ErpOrderStatus.pass.getStatus())).orElse(0);
        logger.info("出库数量:{} 原始数量:{}", outOrderNum, orderNum);
        if (outOrderNum >= orderNum) {
            //更新为已完成
            orderMapper.updateOrderStatus(originOrderSn, OrderStatus.completed.getStatus());
        } else {
            //更新为部分销售
            orderMapper.updateOrderStatus(originOrderSn, OrderStatus.partialSales.getStatus());
        }
    }

    private void insertOutOrInOweGoods(ErpOrderItem item, int userId, int mode) {
        if (item.getOrderItemId() == 0) {
            return;
        }
        OrderItem orderItem = orderItemMapper.selectById(item.getOrderItemId());
        if (orderItem != null) {
            ErpOweGoodsItem oweItem = new ErpOweGoodsItem();
            oweItem.setMode(mode);
            oweItem.setNumber(orderItem.getGoodsNum() - item.getGoodsNum());
            oweItem.setGoodsId(orderItem.getGoodsId());
            oweItem.setSinglePrice(orderItem.getShopPrice());
            oweItem.setOrderSn(orderItem.getOrderSn());
            oweItem.setItemId(orderItem.getId());
            oweItem.setOweTime(LocalDateTime.now());
            oweItem.setUserId(userId);
            oweItem.setOewnumber(oweItem.getNumber());
            oweItem.setSupplierId(erpGoodMapper.selectSupplierById(orderItem.getGoodsId()));
            erpOweGoodsItemMapper.insert(oweItem);
            orderItem.setIsInto(1);
            orderItem.setIsOut(1);
            orderItemMapper.updateById(orderItem);
        }
    }

    @Override
    public List<ErpOweItemList> getOweTtemListByMode(int mode, String orderSn, String start, String end) {
        Stopwatch watch = Stopwatch.createStarted();
//        List<ErpOweItemList> list = new ArrayList<>();
//        List<String> orders = erpOweGoodsItemMapper.getOrderSnsByMode(mode);
//        for (String orderSn : orders) {
//            ErpOweItemList oweItemList = new ErpOweItemList();
//            oweItemList.setOrderSn(orderSn);
//            ErpOrder erpOrder = getErpOrder(orderSn);
//            if (erpOrder != null) {
//                List<AdminUser> users = adminUserMapper.selectByName(erpOrder.getOperator());
//                if (users.isEmpty()) {
//                    oweItemList.setAdminUser(new AdminUser());
//                } else {
//                    oweItemList.setAdminUser(users.get(0));
//                }
//                //获取对应订单追加进入
//                oweItemList.setItems(getOweTempOrder(erpOrder.getOrderInfo(), mode));
//                list.add(oweItemList);
//            } else {
//                //表示为原始订单号
//                Order order = orderMapper.selectByOrderSn(orderSn);
//                if (order == null) {
//                    throw new RuntimeException("没有发现对应的订单号.");
//                }
//                AdminUser adminUser = adminUserMapper.selectById(order.getUserId());
//                oweItemList.setAdminUser(adminUser);
//                oweItemList.setItems(getOweTempOrder(order.getOrderSn(), mode));
//                list.add(oweItemList);
//            }
//        }
        List<ErpOweItemList> list = getOweItemListByModeForFast(mode, orderSn, start, end);
        watch.stop();
        logger.info("欠缺货列表耗时:{}", watch.toString());
        // 欠货耗时： 8.418 s  -- 4.338s
        // 缺货耗时: 3.581 s   -- 1.546s

        return list;
    }

    @Override
    public List<ErpOweItemList> getItemListForEnded() {
        List<ErpOweItemList> list = getOweItemListByModeForFast(3, "", "", "");
        return list;
    }


    @Cacheable(value = "app", key = "'owe-list' + #mode", sync = true)
    public List<ErpOweItemList> getOweItemListByModeForFast(int mode, String orderSn, String start, String end) {
        // 欠货耗时： 8.418 s  -- 4.338s
        // 缺货耗时: 3.581 s   -- 1.546s
        List<ErpOweItemList> list = new ArrayList<>();
        List<String> orders = erpOweGoodsItemMapper.getOrderSnsByMode(mode, orderSn, start, end);
        for (String order : orders) {
            ErpOweItemList oweItemList = new ErpOweItemList();
            oweItemList.setOrderSn(order);
            AdminUser adminUser = adminUserMapper.selectUserByOrderSn(order);
            oweItemList.setAdminUser(adminUser);
            oweItemList.setItems(getOweTempOrder(order, mode));
            //操作人
            oweItemList.setOperator(Optional.ofNullable(erpOweGoodsItemMapper.selectOperatorByOrderSn(order)).orElse("未记录"));
            //结束时间
            oweItemList.setTimeOfEnded(Optional.ofNullable(erpOweGoodsItemMapper.selectLocalDateTimeByOrderSn(order)).orElse(LocalDateTime.now()));
            list.add(oweItemList);
        }
        return list;
    }

    @Override
    public List<ErpTempOrderItem> getOweTempOrder(String orderSn, int mode) {
        QueryWrapper<ErpOweGoodsItem> itemQueryWrapper = new QueryWrapper<>();
        itemQueryWrapper.eq("order_sn", orderSn)
                .eq("mode", mode).ne("number", 0);
        List<ErpOweGoodsItem> erpOweGoodsItems = erpOweGoodsItemMapper.selectList(itemQueryWrapper);
        List<ErpTempOrderItem> tempOrderItems = new ArrayList<>(erpOweGoodsItems.size());
        if (erpOweGoodsItems.isEmpty()) {
            return new ArrayList<>();
        }

        Integer index = orderItemMapper.selectMinId(orderSn);
        int modeType = 0;
        for (ErpOweGoodsItem item : erpOweGoodsItems) {
            ErpGoods goods = erpGoodMapper.selectById(item.getGoodsId());
            if (goods != null) {
                if (oweItem2TempItem(item, goods, index - 1, modeType) != null) {
                    tempOrderItems.add(oweItem2TempItem(item, goods, index - 1, modeType));
                }
            }
        }
        return tempOrderItems;
    }

    @Override
    public ErpTempOrderItem oweItem2TempItem(final ErpOweGoodsItem x, final ErpGoods goods, int index, int modeType) {
        ErpTempOrderItem orderItem = new ErpTempOrderItem();

        ErpWarehouse warehouse = erpWarehouseMapper.selectListOfSearchs(goods.getWhId());
        orderItem.setOweTime(x.getOweTime());
        orderItem.setGoodsId(x.getGoodsId());
        if (warehouse != null) {
            orderItem.setGoodsList(warehouse.getId());
            orderItem.setGoodsListName(warehouse.getWarehouseName());
            orderItem.setDefaultWarehouse(warehouse);
        } else {
            orderItem.setGoodsList(0);
            orderItem.setGoodsListName("");
        }

        Brand brand = brandMapper.selectById(goods.getBrandId());

        orderItem.setGoodsName(goods.getGoodsName());
        orderItem.setGoodsNum(x.getNumber());
        orderItem.setGoodsPrice(x.getSinglePrice());
        orderItem.setBrandName(brand.getBrandName());
        orderItem.setGoodsDesc(goods.getGoodsDesc());
        orderItem.setPAddress(goods.getPAddress());
        orderItem.setSupplier(supplierMapper.selectById(goods.getSuppliersId()));
        orderItem.setNumberUnit(String.valueOf(goods.getNumberUnit()));
        orderItem.setSpecifications(goods.getSpecifications());
        orderItem.setOweItem(x.getId());
        orderItem.setStock(goods.getGoodsNumber());
        if (goods.getDiscount() == 0) {
            orderItem.setDiscount(BigDecimal.ONE);
        } else {
            orderItem.setDiscount(BigDecimal.valueOf(goods.getDiscount()));
        }
        orderItem.setOrderItemId(x.getItemId());
        Integer centralized = Optional.ofNullable(brandMapper.selectCentralizedPurchasing(brand.getBrandName())).orElse(0);
        orderItem.setCentralizedPurchasing(centralized);
        ErpCategory category = erpCategoryMapper.selectById(goods.getCatId());
        if (category != null) {
            orderItem.setGoodsUnit(category.getMeasureUnit());
        }
        //小单位
        SmallUnit smallUnit = smallUnitMapper.selectById(goods.getSmallunitId());
        if (smallUnit == null) {
            orderItem.setGoodsUnit("件");
        } else {
            orderItem.setGoodsUnit(smallUnit.getName());
        }

        orderItem.setIndex(x.getItemId() - index);

        return orderItem;
    }

    /**
     * 设置x的orderItem为以出库状态
     */
    @Override
    public void outStatusChange(OrderItem orderItem, ErpOrder order) {
        if (orderItem != null && order.getMode() == ErpOrderController.MODE_OUT) {
            orderItem.setIsOut(1);
            orderItem.setIsInto(1);
            orderItemMapper.updateById(orderItem);
        }
    }


    @Override
    public void oweGoodsByIn(OrderItem orderItem, ErpOrderItem x, ErpOrder order, int userId, int supplierId) {
        if (x.getOrderItemId() != 0) {
            if (orderItem != null && order.getMode() == ErpOrderController.MODE_IN) {
                ErpOweGoodsItem oweGoodsItem = new ErpOweGoodsItem();
                oweGoodsItem.setGoodsId(x.getGoodsId());
                oweGoodsItem.setItemId(orderItem.getId());
                oweGoodsItem.setMode(0);
                oweGoodsItem.setNumber(x.getOweNum());
                oweGoodsItem.setOrderSn(orderItem.getOrderSn());
                oweGoodsItem.setOweTime(LocalDateTime.now());
                oweGoodsItem.setSinglePrice(x.getGoodsPrice());
                oweGoodsItem.setUserId(userId);
                oweGoodsItem.setSupplierId(supplierId);
                oweGoodsItem.setOewnumber(x.getOweNum());
                //   logger.info("添加欠缺货数据:{}", oweGoodsItem);
                if (x.getOweNum() > 0) {
                    erpOweGoodsItemMapper.insert(oweGoodsItem);
                }
            } else {
                throw new RuntimeException("订单项未发现.");
            }
        }
    }

    /**
     * 缺货功能  /出库
     * 缺货不会直接减去数据库里的商品但是会记录下来.
     *
     * @param x     erpOrderItem
     * @param order erpOrder
     */
    @Override
    public void oweGoodsByOut(OrderItem orderItem, ErpOrderItem x, ErpOrder order, int userId, int supplierId) {
        if (x.getOrderItemId() != 0 || (order.getOriginOrderSn() != null && !"".equals(order.getOriginOrderSn()))) {
            if (orderItem == null) {
                orderItem = orderItemMapper.selectBySnAndGoodsId(order.getOriginOrderSn(), x.getGoodsId());
            }
            if (orderItem != null && order.getMode() == ErpOrderController.MODE_OUT) {

                ErpOweGoodsItem oweGoodsItem = new ErpOweGoodsItem();
                oweGoodsItem.setGoodsId(x.getGoodsId());
                oweGoodsItem.setItemId(orderItem.getId());
                oweGoodsItem.setMode(1);
                int oweNumber = orderItem.getGoodsNum() - x.getGoodsNum();
                if (oweNumber > 0) {
                    oweGoodsItem.setNumber(oweNumber);
                    x.setOweNum(oweNumber);
                    if (x.getOrderItemId() == 0) {
                        x.setOrderItemId(orderItem.getId());
                    }

                    oweGoodsItem.setOrderSn(order.getOriginOrderSn());
                    oweGoodsItem.setOweTime(LocalDateTime.now());
                    oweGoodsItem.setSinglePrice(x.getGoodsPrice());
                    oweGoodsItem.setUserId(userId);
                    oweGoodsItem.setSupplierId(supplierId);
                    oweGoodsItem.setOewnumber(oweNumber);
                    logger.info("添加欠缺货数据:{}", oweGoodsItem);
                    int i = erpOweGoodsItemMapper.insert(oweGoodsItem);
                }
            } else {
                throw new RuntimeException("订单项未发现.");
            }
        }
    }

    public void oweGoodsByOut(OrderItem orderItem, Integer userid) {
        ErpOweGoodsItem oweGoodsItem = new ErpOweGoodsItem();
        oweGoodsItem.setGoodsId(orderItem.getGoodsId());
        oweGoodsItem.setItemId(orderItem.getId());
        oweGoodsItem.setMode(1);
        oweGoodsItem.setNumber(orderItem.getGoodsNum());
        oweGoodsItem.setOrderSn(orderItem.getOrderSn());
        oweGoodsItem.setOweTime(LocalDateTime.now());
        oweGoodsItem.setSinglePrice(orderItem.getShopPrice());
        oweGoodsItem.setUserId(userid);
        oweGoodsItem.setSupplierId(orderItem.getSuppliersId());
        oweGoodsItem.setOewnumber(orderItem.getGoodsNum());
        logger.info("添加欠缺货数据:{}", oweGoodsItem);
        erpOweGoodsItemMapper.insert(oweGoodsItem);
    }


    /**
     * 对仓库商品进行修改 如果存在便添加商品,如果不存在就创建商品
     *
     * @param item
     * @param x
     */
    @Override
    public void intserOrUpdateWarehouseItem(ErpWarehouseItem item, ErpOrderItem x) {
        if (item == null) {
            item = new ErpWarehouseItem();
            item.setGoodsId(x.getGoodsId());
            item.setWhId(x.getGoodsList());
            item.setStock(x.getGoodsNum());
            warehouseItemMapper.insert(item);
        } else {
            item.setStock(item.getStock() + x.getGoodsNum());
            warehouseItemMapper.updateWorderItem(item);
        }
    }


    private void warehouseItemFor(ErpWarehouseItem item, ErpOrderItem x, int number, int mode) {
        if (item == null) {
            item = new ErpWarehouseItem();
            item.setGoodsId(x.getGoodsId());
            item.setWhId(x.getGoodsList());
            if (mode == 0) {
                item.setStock(number);
            } else {
                item.setStock(0);
            }
            warehouseItemMapper.insert(item);
        } else {
            if (mode == 0) {
                item.setStock(item.getStock() + number);
            } else {
                item.setStock(item.getStock() - number);
            }
            warehouseItemMapper.updateById(item);
        }
    }

    @Override
    public boolean deleteErpOrder(String orderSn) {
        if (erpOrderMapper.deleteByOrderSn(orderSn)) {
            erpOrderItemMapper.deleteItemsByOrderSn(orderSn);
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public boolean endedOwe(String orderSn, AdminUser user) {

        List<ErpOweGoodsItem> oweGoodsItems = erpOweGoodsItemMapper.selectListByOrderSn(orderSn);
        if (orderSn.startsWith("CGDD")) {
            logger.info("订单经销商扣款, 订单号:{}", orderSn);
            for (ErpOweGoodsItem oweGoodsItem : oweGoodsItems) {
                //退款单金额 供应商减去金额
                BigDecimal refundPrice = oweGoodsItem.getSinglePrice().multiply(BigDecimal.valueOf(oweGoodsItem.getNumber()));
                logger.info("supplierID:{}, 减去金额:{}", oweGoodsItem.getSupplierId(), refundPrice);
                supplierMapper.deleteSuplierBalance(oweGoodsItem.getSupplierId(), refundPrice);
            }
        } else {
            logger.info("客户订单,不需要扣款. 订单号:{}", orderSn);
        }

        //出库单终结
        //记录终结人和终结时间
        return erpOweGoodsItemMapper.changeOrderSnToEnded(orderSn, user.getUserName(), LocalDateTime.now());
    }

//    public boolean endedOwe2(String orderSn) {
//        //生成一个退款单 TK,与CGDD单号管理,状态为2(已完成)
//
//        ErpOrder order = new ErpOrder();
//        order.setOriginOrderSn(orderSn);
//        order.setStatus(ErpOrderStatus.pass.getStatus());
//        order.setOrderInfo("TK" + Instant.now().toEpochMilli());
//        order.setCreateTime(LocalDateTime.now());
//        order.setExecuteTime(LocalDateTime.now());
//        order.setMode(2);
//
//        if (erpOrderMapper.insert(order) == 1) {
//            List<ErpOweGoodsItem> oweGoodsItems = erpOweGoodsItemMapper.selectListByOrderSn(orderSn);
//            for (ErpOweGoodsItem oweGoodsItem : oweGoodsItems) {
//                ErpOrderItem erpOrderItem = new ErpOrderItem();
//                erpOrderItem.setOrderSn(order.getOrderInfo());
//                erpOrderItem.setGoodsNum(oweGoodsItem.getNumber());
//                erpOrderItem.setGoodsPrice(oweGoodsItem.getSinglePrice());
//                erpOrderItemMapper.insert(erpOrderItem);
//                //退款单金额 供应商减去金额
//                BigDecimal refundPrice = oweGoodsItem.getSinglePrice().multiply(BigDecimal.valueOf(oweGoodsItem.getNumber()));
//                supplierMapper.deleteSuplierBalance(oweGoodsItem.getSupplierId(), refundPrice);
//            }
//
//        } else {
//            throw new RuntimeException("生成退款单失败!");
//        }
//
//        //出库单终结
//        return erpOweGoodsItemMapper.changeOrderSnToEnded(orderSn);
//    }


    @Override
    public boolean rkBack(String orderSn) {
        ErpOrder order = erpOrderMapper.selectErpOrderByOrderSn(orderSn);
        if (order == null) {
            throw new RuntimeException("不存在此订单");
        }
        if (order.getStatus() != ErpOrderStatus.pass.getStatus()) {
            throw new RuntimeException("只支持完成的出库单回滚!");
        }
        if (order.getMode() != ErpOrderController.MODE_IN) {
            throw new RuntimeException("订单不是入库单");
        }
        List<ErpOrderItem> orderItems = erpOrderItemMapper.selectOrderItemsByOrderId(order.getOrderId());
        for (ErpOrderItem item : orderItems) {
            orderItemRecovery(item);
        }
        order.setStatus(ErpOrderStatus.draft.getStatus());
        return erpOrderMapper.updateById(order) == 1;
    }

    @Transactional
    public void orderItemRecovery(ErpOrderItem item) {
        if (item.getOrderItemId() != 0) {
            orderItemMapper.setOrderIntoAndOutForZero(item.getOrderItemId());
        }
        if (item.getOweItem() > 0) {
            //删除欠货单..
            erpOweGoodsItemMapper.deleteByItemId(item.getOrderItemId());
        }
        if (!warehouseItemMapper.subGoodsNumber(item.getGoodsId(), item.getGoodsList(), item.getGoodsNum())) {
            throw new RuntimeException(item.getGoodsName() + " 商品库位异常!");
        }
        erpGoodMapper.subGoodsNum(item.getGoodsId(), item.getGoodsNum());
    }


    @Override
    public List<Order> getRemoteOutOrder(List<String> notin, AdminUser user) {
        QueryWrapper<ErpOrder> wrapper = new QueryWrapper<>();
        wrapper.notIn("order_info", notin)
                .eq("mode", 1).eq("status", 2).eq("store_id", user.getUserId());
        List<ErpOrder> orders = erpOrderMapper.selectList(wrapper);
        List<Order> orderList = new ArrayList<>();
        for (ErpOrder erpOrder : orders) {
            Order order = new Order();
            order.setOrderSn(erpOrder.getOrderInfo());
            order.setSupplierName(erpOrder.getSupplierName());
            order.setItems(tempOrderItemMapper.listByOrderItem(erpOrder.getOrderId()));
            if (!order.getItems().isEmpty()) {
                orderList.add(order);
            }
        }
        return orderList;
    }

    @Override
    public List<RepertoryVOByYSH> salesPageByYSHKC(long start, long end, int cat_id,
                                                   int supplier_id, String goodsName) {
        List<Integer> integers = erpOrderMapper.getGoodsIds(start, end, cat_id, supplier_id, goodsName.trim());
        List<Integer> integers1 = erpOrderMapper.getGoodsIds1(start, end, cat_id, supplier_id, goodsName.trim());
        List<Integer> integers2 = erpOrderMapper.getGoodsIds2(start, end, cat_id, supplier_id, goodsName.trim());
        integers.addAll(integers1);
        integers.addAll(integers2);

        //去重
        for (int i = 0; i < integers.size() - 1; i++) {
            for (int j = integers.size() - 1; j > i; j--) {
                if (integers.get(j).intValue() == integers.get(i).intValue()) {
                    integers.remove(j);
                }
            }
        }

        List<RepertoryVOByYSH> repertoryVOByYSHES = new ArrayList<>();
        for (Integer integer : integers) {
            RepertoryVOByYSH repertoryVOByYSH = new RepertoryVOByYSH();
            repertoryVOByYSH = erpOrderMapper.getR(start, end, integer);
            repertoryVOByYSHES.add(repertoryVOByYSH);
        }
        return repertoryVOByYSHES;
    }
}
